﻿using AutoMapper;
using DocumentFormat.OpenXml.Wordprocessing;
using MediatR;
using MyMES.Domain.W.Liststructure;
using MyMES.Domain.zmc;
using MyMES.Error;
using MyMES.Infrastructure.Interface;
using MyMES.Read.API.Application.Commends.Incominginformations;
using MyMES.Read.API.Dtos;

namespace MyMES.Read.API.Application.CommendHandlers.Incominginformations
{
    public class GetMateArrivaCommendHandlers : IRequestHandler<GetMateArrivaCommends, APIResult<List<MateArrivaDtos>>>
    {

        private readonly IBaseRepository<Materialmanagement>  MaterRepository;
        private readonly IBaseRepository<Arrivalnotice>   ArrivalRepository;
        private readonly IMapper mapper;

    

        public GetMateArrivaCommendHandlers(IBaseRepository<Materialmanagement> materRepository, IBaseRepository<Arrivalnotice> arrivalRepository, IMapper mapper)
        {
            MaterRepository = materRepository;
            ArrivalRepository = arrivalRepository;
            this.mapper = mapper;
        }

        /// <summary>
        /// 获取物料入库信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<APIResult<List<MateArrivaDtos>>> Handle(GetMateArrivaCommends request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<List<MateArrivaDtos>> result = new APIResult<List<MateArrivaDtos>>();
                result.Code = APIEnum.查询成功;
                result.Msg = "查询成功";
                var sql = " SELECT a.*,b.Materialnumber,b.Materialname,b.Specification,b.Unit FROM arrivalnotice a LEFT JOIN materialmanagement b  on a.MId=b.MId   ORDER BY a.NoticeId DESC;";
                var maters = await MaterRepository.SelectAsync(sql);
                var arrivas = await ArrivalRepository.SelectAsync(sql);

                var rearrivas = mapper.Map<List<MateArrivaDtos>>(arrivas);
                var rematers = mapper.Map<List<MateArrivaDtos>>(maters);
                foreach (var item in rearrivas)
                {
                    item.Materialnumber = rematers.FirstOrDefault(x => x.MId == item.MId)?.Materialnumber;
                    item.Materialname = rematers.FirstOrDefault(x => x.MId == item.MId)?.Materialname;
                    item.Specification = rematers.FirstOrDefault(x => x.MId == item.MId)?.Specification;
                    item.Unit = rematers.FirstOrDefault(x => x.MId == item.MId).Unit;

                }
                result.data = rearrivas;
                return result;
            }
            catch (Exception e)
            {

                throw;
            }
        }
    }
}
